<template>
  <div v-if="getVisible">
    <a-drawer placement="right" :visible="getVisible" @close="closeModelView" width="512">
      <div>
        <!-- 审批人页面 -->
        <div v-if="nodeData && nodeData.isRow">
          <a-tabs default-active-key="1" @change="callback">
            <a-tab-pane key="1" tab="审批人设置">
              <div class="w100">
                <a-radio-group
                  name="userRadioGroup"
                  class="w100 border_b"
                  @change="onChange1"
                  v-model="checkedIndex"
                >
                  <label v-for="(item, index) in radioList" :key="index">
                    <a-radio
                      class="mb20"
                      :value="index"
                      style="width: 33%; margin-right: 0"
                      >{{ item.label }}</a-radio
                    >
                  </label>
                </a-radio-group>

                <!-- 修改标题 -->
                <div>
                  <a-input v-model="nodeData.title"></a-input>
                </div>

                <div class="spr_content" v-if="checkedIndex !== ''">
                  <!-- 指定成员 -->
                  <div class="c_title">{{ radioList[checkedIndex].label }}</div>
                  <div v-if="checkedIndex == 0">
                    <a-button type="primary" @click="showAddUserModal">选择成员</a-button>
                    <a-row>
                        <a-col v-for="item in nodeData.data.selectUsername" :key="item" :span="6">{{item}}</a-col>
                    </a-row>
                  </div>
                  <div v-if="checkedIndex == 1">
                    <div>选择领导层级</div>
                    <a-radio-group v-model="nodeData.data.candidateGroups1[0]">
                      <a-radio v-for="item in leadTypeList" class="radio_block" :key="item.type" :value="item.type">
                       {{item.label}}
                      </a-radio>
                    </a-radio-group>
                  </div>

                  <div v-if="checkedIndex == 2">
                    <a-button type="primary" @click="showAddGroupModal">选择角色</a-button>
                    <a-row>
                        <a-col v-for="item in nodeData.data.selectUsername" :key="item" :span="6">{{item}}</a-col>
                    </a-row>
                  </div>
                </div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="2" tab="权限设置" force-render>
              <div class="qx_view">
                <!-- <a-row class="mb10">
                    <a-col :span="12">控件</a-col>
                   <a-radio-group name="mianRadio" :default-value="1">
                    <a-radio :value="1">隐藏</a-radio>
                    <a-radio :value="2">仅查看</a-radio>
                    <a-radio :value="3">可编辑</a-radio>
                  </a-radio-group>
                </a-row> -->
                <div v-if="qxList.list.length>0">
                  <a-row class="mb10" v-for="item in qxList.list" :key="item.key">
                    <a-col :span="12">{{item.name}}</a-col>
                    <a-radio-group :name="item.model" :value="qxChangeData[item.model]" @change="e=>qxChange(e,item.model)">
                      <a-radio :value="2">隐藏</a-radio>
                      <a-radio :value="0">仅查看</a-radio>
                      <a-radio :value="1">可编辑</a-radio>
                    </a-radio-group>
                  </a-row>
                </div>

              </div>
            </a-tab-pane>
          </a-tabs>
        </div>

        <!-- 条件设置 -->
        <div v-else>
          <div class="c_title c_s16">条件设置</div>
          <a-input v-model="nodeData.title"></a-input>
          <div>
            <div class="c_title">请选择条件设置</div>
            <a-row :gutter="10">
              <a-col :span="6">
                <a-select style="width: 100%" label-in-value v-model="nodeData.data.type" @change="typeChange">
                  <a-select-option v-for="item in tjTypeList" :key="item.colName">{{ item.colComment }}</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-select style="width: 100%" label-in-value v-model="nodeData.data.mathType" @change="mathTypeChange">
                  <a-select-option v-for="item in tjMathType" :key="item.type">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-input v-model="nodeData.data.value1"></a-input>
              </a-col>
              <a-col :span="6" v-if="nodeData.data.mathType=='<>'">
                <a-input v-model="nodeData.data.value2"></a-input>
              </a-col>
            </a-row>
          </div>
        </div>
      </div>

      <div class="end_button">
        <a-button :style="{ marginRight: '8px' }" @click="closeModelView"
          >取消</a-button
        >
        <a-button type="primary" @click="changeFatherNodeData">确定</a-button>
      </div>
    </a-drawer>
    <div>
      <a-modal
        :width="800"
        cancelText="取消"
        okText="确定"
        v-model="addUserModal"
        :title="addType == 'user'?'指定成员':'选择角色'"
        @ok="changeNodeData"
      >
        <a-row v-if="addType == 'user'" class="">
          <a-col class="user_list" :span="7">
            <a-tree
              v-model="checkedKeys"
              checkStrictly
              :tree-data="treeData"
              :replaceFields="replaceFields"
              @select="onSelect"
            />
          </a-col>
          <a-col class="user_list" :span="17">
            <!-- 人员表格 -->
            <a-table
              :columns="columns"
              bordered
              rowKey="USERID"
              :loading="tableLoading"
              :data-source="userData"
              :rowSelection="userRowSelection"
              :pagination="false"
              size="small"
            >
              <a slot="name" slot-scope="text">{{ text }}</a>
            </a-table>
          </a-col>
        </a-row>
        <div v-else-if="addType == 'group'">
          <!-- 角色表格 -->
          <a-table
            :columns="groupColumns"
            bordered
            rowKey="XTJS_DM"
            :data-source="groupData"
            :rowSelection="groupRowSelection"
            :pagination="false"
            size="small"
          >
            <a slot="name" slot-scope="text">{{ text }}</a>
          </a-table>
        </div>
      </a-modal>
    </div>
  </div>
</template>
<script>
// 审批人list
const radioList=[
  {
    label: "指定成员",
    id: "radio_0",
  },
  {
    label: "本部门领导",
    id: "radio_1",
  },
  {
    label: "指定角色",
    id: "radio_2",
  },
  {
    label: "申请人本人",
    id: "radio_3",
  },
];
// 用户table表头
const columns = [
  {
    title: "序号",
    dataIndex: "INDEX",
    align:"center",
    width: 50,
    key: "INDEX",
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    title: "登录名",
    dataIndex: "USERNAME",
    key: "USERNAME",
    width: 120,
  },
  {
    title: "姓名",
    dataIndex: "CZRY_MC",
    key: "CZRY_MC",
    width: 120,
  },
  {
    title: "所示部门",
    dataIndex: "ZZJG_MC",
    key: "ZZJG_MC",
    ellipsis: true,
  },
];
// 角色table表头
const groupColumns = [
  {
    title: "序号",
    dataIndex: "INDEX",
    key: "INDEX",
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    title: "角色名称",
    dataIndex: "XTJS_MC",
    key: "XTJS_MC",
  },
  {
    title: "创建部门",
    dataIndex: "ZZJG_MC",
    key: "ZZJG_MC",
  },
  {
    title: "创建人",
    dataIndex: "LRR_MC",
    key: "LRR_MC",
  },
];
// 用户table分页
const userPagination = {
  defaultCurrent: 1, //默认的当前页数
  defaultPageSize: 5, //每页显示几条数据
  total: 0, //总数
  showTotal: (total) => `共 ${total} 条`, // 显示总数
  current: 1, //当前页数 v-model
  showQuickJumper: false, //是否显示直通车
};
// 角色table分页
const groupPagination = {
  defaultCurrent: 1, //默认的当前页数
  defaultPageSize: 5, //每页显示几条数据
  total: 0, //总数
  showTotal: (total) => `共 ${total} 条`, // 显示总数
  current: 1, //当前页数 v-model
  showQuickJumper: false, //是否显示直通车
};
// 条件设置类型list
const tjMathType=[{
  label:"大于",
  type:">"
},{
  label:"大于等于",
  type:">="
},{
  label:"等于",
  type:"=="
},{
  label:"小于",
  type:"<"
},{
  label:"小于等于",
  type:"<="
},{
  label:"介于",
  type:"<>"
}];
// 选择用户时部门领导list
const leadTypeList=[{
  label:"直接上级",
  type:"&type:creator?Superior"
},{
  label:"第二级上级",
  type:"&type:creator?Superior2"
},{
  label:"第三级上级",
  type:"&type:creator?Superior3"
}];

import {
  selectZzjgTree,
  selectYhListByZzjg,
  selectQxglJsqx,
  getFlowFormColumns,
  getFlowFormById
} from "@/common/js/baseReq";
import {getQueryString} from '@/utils/index'
// import { delete } from 'vue/types/umd';
export default {
  data() {
    return {
      getVisible: this.visible,//抽屉是否展示
      nodeData: this.currentNode, //节点信息
      radioList,
      checkedIndex: "",
      addUserModal: false,
      // 权限
      qxList: [],
      getQxChangeData:{},
      qxChangeData:{},
      // 条件
      tjTypeList: [],
      tjMathType,


      // 添加类型："user"用户，“group”角色
      addType: "",

      // tree 组织树
      treeData: [],
      replaceFields: { children: "children", title: "ZZJG_MC", key: "ZZJG_DM" },
      checkedKeys: [],
      //table 用户
      tableLoading:false,
      userData: [],
      columns,
      userPagination,
      userSelectedRowKeys:[],//多选的key
      selectUsername:[],

      //table 角色
      groupPagination,
      groupData: [],
      groupColumns,
      groupSelectedRowKeys:[],
      groupSelectedRowKeys1:[],//多选key转换成后台所需数据
      // 条件填写
      tjData:"",
      leadTypeList,
    };
  },
  props: {
    visible: {
      type: Boolean,
      defult: false,
    },
    currentNode: {
      type: Object,
      defult: {},
    },
  },
  created() {
    this.selectZzjgTree();
    this.selectQxglJsqx();
    this.getTjTypeList();
    this.getFlowFormById(); //获取权限list
  },
  mounted() {},
  computed: {
    userRowSelection() {
      const { userSelectedRowKeys } = this;
      return {
        userSelectedRowKeys,
        onChange: this.onUserSelectChange,
        hideDefaultSelections: true,
        onSelection: this.onSelection,
      };
    },
    groupRowSelection() {
      const { groupSelectedRowKeys } = this;
      return {
        groupSelectedRowKeys,
        onChange: this.onGroupSelectChange,
        hideDefaultSelections: true,
        onSelection: this.onSelection,
      };
    },
  },
  methods: {
    // 获取条件list
    getTjTypeList(){
      let formId=getQueryString('formId')
      let formdata={
        formId:formId,
      }
      getFlowFormColumns(formdata).then(res=>{
        if(res.data.code==0){
          this.tjTypeList=res.data.data
        }
      })
    },
    // 获取组织树接口
    selectZzjgTree() {
      selectZzjgTree().then(res=>{
        if(res.status=='200'){
          let list=res.data
          this.dataToTree(list)
        }
      })
    },
    /**
     * list：一维数组
     * 将获取的组织树的一维数组转换成树
     */
    dataToTree(list) {
      if (!list || !list.length) return [];
      let map = {};
      for (let item of list) {
        map[item.ZZJG_DM] = item;
      }
      let nodes = [];
      for (let lis of list) {
        let p = map[lis.SJ_ZZJG_DM];
        let parentId = lis.SJ_ZZJG_DM;
        if (p) {
          for (let lis2 of list) {
            if (lis2.ZZJG_DM == parentId) {
              //当内层循环的ID== 外层循环的parendId时，（说明有children），需要往该内层id里建个children并push对应的数组；
              if (!lis2.children) {
                lis2.children = [];
              }
              lis2.children.push(lis);
            }
          }
        }
      }
      list = list.filter((ele) => !map[ele.SJ_ZZJG_DM]);
      this.treeData = list;
    },

    // 审批人设置切换
    onChange1(e) {
      let checkedIndex=e.target.value;
      this.checkedIndex = checkedIndex
      if(checkedIndex===0){
        this.nodeData.data={
          type:"0",
          candidateUsers:[]
        }
      }else if(checkedIndex===1){
        this.nodeData.data={
          type:"1",
          candidateGroups1:['&type:creator?Superior']
        }
      }else if(checkedIndex===2){
        this.nodeData.data={
          type:"2",
          candidateGroups:[],
          candidateGroups1:[]
        }
      }else if(checkedIndex===3){
        this.nodeData.data={
          type:"3",
          candidateGroups1:['&type:creator?Self']
        }
      }
    },

    // 关闭抽屉
    closeModelView() {
      this.getVisible = false;
      this.$emit("closeEvent", this.getVisible);
    },

    //修改节点数据(表格选择)
    changeNodeData() {
      if(this.addType==='user'){
          this.nodeData.data.candidateUsers=this.userSelectedRowKeys
          this.nodeData.data.selectUsername=this.selectUsername
      }else if(this.addType==='group'){
          this.nodeData.data.candidateGroups=this.groupSelectedRowKeys
          this.nodeData.data.candidateGroups1=this.groupSelectedRowKeys1
          this.nodeData.data.selectUsername=this.selectUsername
      }
      this.addUserModal=false
    },

    //条件输入框修改
    tjChange(e){
      this.nodeData.data=e.target.value
    },

    // 抽屉确定事件，修改nodeData
    changeFatherNodeData(){
      let nodeData=this.nodeData
      if(nodeData && nodeData.isRow){
        if(nodeData.data.type=="0"){
          if(nodeData.data.candidateUsers.length>0){
            nodeData.content="指定成员："+nodeData.data.selectUsername.toString()
          }
          
        }else if(nodeData.data.type=="1"){
          let type=nodeData.data.candidateGroups1.toString()
          let con=type=="&type:creator?Superior"?"直接上级":type=="&type:creator?Superior2"?"第二级上级":type=="&type:creator?Superior3"?"第三级上级":""
          nodeData.content="指定本部门领导："+con
        }else if(nodeData.data.type=="2"){
          if(nodeData.data.selectUsername){
             nodeData.content="指定角色："+nodeData.data.selectUsername.toString()
          }
         
        }else if(nodeData.data.type=="3"){
          nodeData.content="指定申请人本人"
        }else{
          nodeData.data={
            qxData:""
          }
        }

        nodeData.data.qxData=this.qxChangeData
      }else{
        if(nodeData.data.mathType.key=="<>"){
          nodeData.content=nodeData.data.type.label+"介于"+nodeData.data.value1+"和"+nodeData.data.value2+"之间"
        }else{
           nodeData.content=nodeData.data.type.label+nodeData.data.mathType.label+nodeData.data.value1
        }
      }
      this.nodeData=nodeData
      this.closeModelView()
      this.$emit("nodeChange", this.nodeData);
    },
    // 审批人和权限切换
    callback() {},

    // 添加人员model
    showAddUserModal() {
      this.addUserModal = true;
      this.addType = "user";
    },

    // 添加角色model
    showAddGroupModal() {
      this.addUserModal = true;
      this.addType = "group";
    },

    // 组织树选择
    onSelect(selectedKeys, info) {
      if(selectedKeys.length>0){
        this.selectedKeys = selectedKeys;
        this.selectYhListByZzjg();
      }
    },

    /**
     * ZZJG_DM:组织机构id
     * 获取组织下的用户
     */
    selectYhListByZzjg() {
      let formdata = {
        ZZJG_DM: this.selectedKeys[0],
        page: 1,
        pageSize: 1000,
      };
      this.tableLoading=true
      selectYhListByZzjg(formdata).then(res=>{
        this.tableLoading=false
        if(res.data.code==0){
          this.userData=res.data.list
          this.userPagination.total=res.data.list[0]?res.data.list[0].TOTAL:0
        }
      })

    },

    // 用户表格多选事件()
    onUserSelectChange(userSelectedRowKeys,selectedRows) {
      this.userSelectedRowKeys = userSelectedRowKeys;
      let showContent=[]
      for(let item of selectedRows){
        showContent.push(item.CZRY_MC)
      }
      this.selectUsername=showContent
    },

    // 角色表格多选事件
    onGroupSelectChange(groupSelectedRowKeys,selectedRows) {
      this.groupSelectedRowKeys = groupSelectedRowKeys;
      let showContent=[]
      let groupSelectedRowKeys1=[]
      for(let item of selectedRows){
         groupSelectedRowKeys1.push(item.XTJS_MC+'|'+item.XTJS_DM)
         showContent.push(item.XTJS_MC)
      }
      this.selectUsername=showContent
      this.groupSelectedRowKeys1=groupSelectedRowKeys1
    },

    // 获取系统角色
    selectQxglJsqx() {
      var formdata = {
        page: 1,
        pageSize: 1000,
      };
      selectQxglJsqx(formdata).then(res=>{
        if(res.data.code==0){
            // this.groupPagination.total=res.data.data[0].TOTAL
            this.groupData=res.data.data
        }
      })
    },

    // 表格分页事件
    userTableChange(pagination, filters, sorter){
      this.userPagination = pagination;
      this.selectYhListByZzjg()
    },
    groupTableChange(pagination, filters, sorter){
      this.groupPagination = pagination;
      this.selectQxglJsqx()
    },

    // 条件select选择事件
    typeChange(key){
    },
    mathTypeChange(){

    },

    /**
     * 权限设置
     */
    // 获取权限list
    getFlowFormById(){
      let formId=getQueryString('formId')
      let formdata={
        id:formId
      }
      getFlowFormById(formdata).then(res=>{
       
        if(res.data.code==0){
          let getData=res.data.data
          this.qxList=JSON.parse(getData.formSrc)
          let qxData={}
          for(let item of this.qxList.list){
            qxData[item.model]=0
          } 
          this.getQxChangeData=qxData
        }
      })
    },
    //权限选择
    qxChange(e,key){
      this.qxChangeData[key]=e.target.value
      // this.nodeData.data.qxData[key]=e.target.value
      this.qxChangeData = Object.assign({},this.qxChangeData)
    }

  },
  watch: {
    visible(newValue) {
      this.getVisible = newValue;
    },
    currentNode(newValue) {
      if(newValue.type=="2"){
        //该节点是审批人节点
        let type = newValue.data.type?Number(newValue.data.type):"";//审批人类型
        this.checkedIndex = type
        if(type===0){
          this.userSelectedRowKeys=newValue.data.candidateUsers
        }else if(type===2){
          this.groupSelectedRowKeys=newValue.data.candidateGroups
          this.groupSelectedRowKeys1=newValue.data.candidateGroups1
        }
        // 判断数据是否含有权限
        if(newValue.data.qxData){
          this.qxChangeData=newValue.data.qxData
        }else{
          this.qxChangeData=this.getQxChangeData
        }
      }else if(newValue.type=="3"){
        // 该节点是条件节点
        this.tjData=newValue.data?newValue.data:""
        newValue.data=newValue.data?newValue.data:{
          mathType:"",
          type:"",
          value1:"",
          value2:""
        }
      }
      this.nodeData = newValue;
    },
  },
};
</script>

<style scoped>
.w100 {
  width: 100%;
}
.mb20 {
  margin-bottom: 20px;
}
.mb10 {
  margin-bottom: 10px;
}
.border_b {
  border-bottom: 1px solid #e9e9e9;
}
.spr_content {
  margin: 20px 0;
}
.end_button {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  text-align: right;
  z-index: 1;
}
.qx_view input {
  width: 15px;
  height: 15px;
}
.user_list {
  height: 300px;
  overflow: auto;
}
.c_title{
    font-size: 14px;
    color: #333;
    font-weight: 700;
    padding-bottom: 10px;
}
.radio_block{
  display: block;
  height: 30px;
  line-height: 30px;
}
</style>